package com.chuangke.flowable.schedule;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chuangke.admin.entity.SysRole;
import com.chuangke.admin.entity.SysUser;
import com.chuangke.admin.entity.SysUserRole;
import com.chuangke.admin.service.SysRoleService;
import com.chuangke.admin.service.SysUserRoleService;
import com.chuangke.admin.service.SysUserService;
import com.chuangke.common.db.page.CkPageQuery;
import com.chuangke.flowable.service.FlowableService;
import com.chuangke.sms.model.SMSModel;
import com.chuangke.sms.service.SMSService;

import cn.hutool.core.util.StrUtil;

@Configuration
@EnableScheduling
public class TodoRemindScheduleTask {
	
	private static final Logger logger = LoggerFactory.getLogger(TodoRemindScheduleTask.class);

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysRoleService sysRoleService;

	@Autowired
	private SysUserRoleService sysUserRoleService;

	@Autowired
	private FlowableService flowableService;

	@Autowired
	private SMSService smsService;

	@SuppressWarnings({  "rawtypes" })
//	@Scheduled(cron = "0 0 16 * * ?")
	public void configureTasks() {
		logger.warn("执行发送待办任务提醒定时任务时间: " + LocalDateTime.now());

		List<String> nRoleList = Arrays.asList("admin", "manager", "normal_user");

		List<String> roleList = sysRoleService.findList().stream().filter(role -> !nRoleList.contains(role.getName()))
				.map(SysRole::getId).toList();
		logger.warn("查询到需要发送任务的角色{}条 ",roleList.size());
		
		Map<String, List<SysUserRole>> userRoleMap = sysUserRoleService.findAll();
		if (userRoleMap == null || userRoleMap.isEmpty()) {
			logger.warn("未找到角色对应的人员 ");
			return;
		}
		List<SysUserRole> userRoleList = new ArrayList<>();
		for (List<SysUserRole> list : userRoleMap.values()) {
			userRoleList.addAll(list);
		}
		List<String> userIdList = userRoleList.stream()
				.filter(userRole -> roleList.contains(userRole.getRoleId())).map(SysUserRole::getUserId)
				.distinct().toList();

		logger.warn("查询到需要发送任务的人员{}条 ",roleList.size());
		List<SysUser> userList = sysUserService.findMap().values().stream()
				.filter(user -> userIdList.contains(user.getId()) && !StrUtil.isBlank(user.getMobile()))
				.toList();
		logger.warn("查询到需要发送任务的人员并且配置了手机号的人员{}条 ",roleList.size());

		List<SMSModel> models = new ArrayList<>();

		for (SysUser user : userList) {
			Map<String,Object> params = new HashMap<>() ;
			params.put("userId", user.getId()) ;
			IPage result = flowableService.findTodoTask(new CkPageQuery(params));

			if (result.getTotal() <= 0) {
				continue;
			}

			SMSModel model = new SMSModel();
			model.setUserId(user.getId());
			model.setTelphone(user.getMobile());
			model.setMessage(String.format("尊敬的用户您好，您今日尚有%s条待审批事项需要处理，请及时审批。", result.getTotal()));
			models.add(model);
			
			logger.warn(model.getMessage()) ;
		}

		if (!models.isEmpty()) {
			smsService.send(models.toArray(new SMSModel[0]));
		}
		logger.warn("发送短信{}条 ",models.size());
	}

}